<template>
  <div class="cart">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>购物车管理</h2>
        </div>
      </template>

      <el-table :data="cartList" border style="width: 100%">
        <el-table-column prop="medicineName" label="药品名称"></el-table-column>
        <el-table-column prop="price" label="单价" width="100">
          <template #default="scope"> ¥{{ scope.row.price }} </template>
        </el-table-column>
        <el-table-column label="数量" width="150">
          <template #default="scope">
            <el-input-number 
              v-model="scope.row.quantity" 
              :min="1" 
              :max="scope.row.stock" 
              @change="updateQuantity(scope.row)"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="小计" width="120">
          <template #default="scope">
            ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button type="danger" size="small" @click="removeFromCart(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="cart-footer">
        <div class="cart-total">
          总计: <span class="price">¥{{ totalPrice.toFixed(2) }}</span>
        </div>
        <div class="cart-actions">
          <el-button type="primary" @click="checkout">结算</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listItem, updateItem } from '@/api/item'
import { listMedicine } from '@/api/medicine'
import { addOrder } from '@/api/order'

const router = useRouter()

// 购物车列表
const cartList = ref([])

// 计算总价
const totalPrice = computed(() => {
  return cartList.value.reduce((total, item) => {
    return total + item.price * item.quantity
  }, 0)
})

// 获取购物车列表
const getCartList = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    // 获取购物车项目列表
    const itemRes = await listItem({ userId: userInfo.id })

    // 获取药品列表
    const medicineRes = await listMedicine()

    // 合并购物车项目和药品信息
    cartList.value = itemRes.data.map((item) => {
      const medicine = medicineRes.data.find((m) => m.id === item.medicineId)
      return {
        id: item.id,
        medicineName: medicine.medicineName,
        price: medicine.price,
        quantity: item.quantity,
        stock: medicine.stock,
        medicineId: medicine.id,
      }
    })
  } catch (error) {
    console.error('获取购物车列表失败', error)
    ElMessage.error('获取购物车列表失败')
  }
}

// 更新数量
const updateQuantity = async (item) => {
  try {
    await updateItem({
      id: item.id,
      userId: JSON.parse(localStorage.getItem('userInfo') || '{}').id,
      medicineId: item.medicineId,
      quantity: item.quantity
    })
    
    ElMessage.success('数量已更新')
    // 刷新购物车列表
    getCartList()
  } catch (error) {
    console.error('更新失败', error)
    ElMessage.error('更新失败')
  }
}

// 从购物车移除
const removeFromCart = (item) => {
  ElMessageBox.confirm(`确定要从购物车中移除 ${item.medicineName} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        // 这里应该调用API从购物车中移除商品
        // await delCart(item.id)
        cartList.value = cartList.value.filter((i) => i.id !== item.id)
        ElMessage.success('已从购物车移除')
      } catch (error) {
        ElMessage.error('移除失败')
      }
    })
    .catch(() => {})
}

// 清空购物车
const clearCart = () => {
  ElMessageBox.confirm('确定要清空购物车吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        // 这里应该调用API清空购物车
        // await clearCart()
        cartList.value = []
        ElMessage.success('购物车已清空')
      } catch (error) {
        ElMessage.error('清空失败')
      }
    })
    .catch(() => {})
}

// 结算
const checkout = async () => {
  if (cartList.value.length === 0) {
    ElMessage.warning('购物车为空')
    return
  }

  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    
    // 计算订单总金额（单位：分）
    const totalAmount = cartList.value.reduce((total, item) => {
      return total + item.price * item.quantity * 100
    }, 0)

    // 创建订单
    const orderData = {
      userId: userInfo.id,
      orderStatus: 0, // 待支付状态
      totalAmount: totalAmount,
      items: cartList.value.map(item => ({
        medicineId: item.medicineId,
        quantity: item.quantity,
        unitPrice: item.price * 100 // 转换为分
      }))
    }

    await addOrder(orderData)
    ElMessage.success('订单创建成功')
    router.push('/user/order')
  } catch (error) {
    console.error('创建订单失败', error)
    ElMessage.error('创建订单失败')
  }
}

// 初始化
onMounted(() => {
  getCartList()
})
</script>
